function layoutFolderViewPort(layout, node) {
    if (layout == undefined) {
        layout = contentPanel.layout;
    }
    layout.setActiveItem("main-content-folder-panel");
    Ext.Ajax.request({
        url: node.attributes.uri + "/mayUpdate",
        method: "GET",
        params: {
            "user_uri": LoggedInUser.userUri
        },
        success: function() {
            Ext.getDom("main-content-folder-item").innerHTML = "";
            mayUpdateFolderComponents(node);
        },
        failure: function() {
            Ext.getDom("main-content-folder-item").innerHTML = "Read only access allowed";
            Ext.getDom("main-content-folder-addsub").innerHTML = "";
            Ext.getDom("main-content-folder-upload").innerHTML = "";
            Ext.getDom("main-content-folder-delete").innerHTML = "";
            Ext.getDom("main-content-folder-rename").innerHTML = "";
            Ext.getDom("main-content-repository-addsub").innerHTML = "";
            Ext.getDom("main-content-repository-upload").innerHTML = "";
            Ext.getDom("main-content-repository-item").innerHTML = "";
            eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
        }
    });
}

function mayUpdateFolderComponents(node) {
    var deleteDiv = Ext.getDom("main-content-folder-delete");
    deleteDiv.innerHTML = "";

    new Ext.Button({
        id: 'delete-folder-button',
        text: "Delete Folder '" + node.attributes.name + "'",
        renderTo: deleteDiv,
        listeners: {click:
                function() {
                    deleteFolder(node);
                }
        }
    });

    renderSubFolderForm(node);
    var subfolderDiv = Ext.getDom("main-content-folder-addsub");
    Ext.DomHelper.insertHtml("beforeEnd", subfolderDiv, "<br>");

    renderUploadFileForm(node);
    var uploadDiv = Ext.getDom("main-content-folder-upload");
    Ext.DomHelper.insertHtml("beforeEnd", uploadDiv, "<br>");

    renderRenameFolderForm(node);
    var renameDiv = Ext.getDom("main-content-folder-rename");
    Ext.DomHelper.insertHtml("beforeEnd", renameDiv, "<br>");

}


function deleteFolder(node) {
    var parentNodeId = node.parentNode.id;
    var name = node.attributes.name;

    Ext.MessageBox.confirm('Message', 'Delete folder ' + name + '?', function(btn) {
        if (btn == 'yes') {
            Ext.Ajax.request({
                url: node.attributes.uri + "/delete",
                method: "POST",
                success: function() {
                    eventManager.fireStatusMessageEvent({ text: name + "Deleted", level: "info" });
                    expandNode(tree.getNodeById(parentNodeId));
                    eventManager.fireNodeSelectEvent(tree.getNodeById(parentNodeId));
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Delete Failed for " + name, level: "error" });
                }
            });
        }
    });
}

function renderSubFolderForm(node) {
    Ext.getDom("main-content-folder-addsub").innerHTML = "";
    var uri = node.attributes.uri;
    var subfolderFormPanel = new Ext.form.FormPanel({
        id: 'folderAddSubForm',
        title: 'New Folder',
        method: 'POST',
        renderTo: "main-content-folder-addsub",
        border: true,
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                autoWidth: true,
                border: false,
                items: [
                    new Ext.form.TextField({
                        fieldLabel: 'Folder Name',
                        defaultAutoCreate : {tag:"input", size: "40", autocomplete: "off"},
                        name: 'newSubfolder',
                        id: 'newSubfolderId',
                        allowBlank: false,
                        listeners: {
                            focus: function(tf) {
                                Ext.getCmp("addFolderButtonId").enable();
                            }
                        }
                    }),
                    new Ext.Button({
                        id: 'addFolderButtonId',
                        text: 'Add',
                        disabled: false,
                        listeners: {
                            click: function() {
                                var subfolder = Ext.getCmp("newSubfolderId").getValue();
                                if (subfolder == undefined || subfolder.length < 1) {
                                    Ext.MessageBox.alert("Folder name is invalid, can not be blank or contain illegal characters");
                                    return false;
                                }

                                var postUrl = uri + "/" + subfolder + "/create";
                                Ext.Ajax.request({
                                    url: postUrl,
                                    method: "POST",
                                    success: function() {
                                        eventManager.fireStatusMessageEvent({ text: "Folder " + subfolder + " Added Successfully", level: "info" });
                                        expandNode(node);
                                        eventManager.fireNodeSelectEvent(node);
                                    },
                                    failure: function() {
                                        eventManager.fireStatusMessageEvent({ text: "Failed to add New Folder", level: "error" });
                                    }
                                });
                            }
                        }
                    })
                ]
            })
        ]
    });
    subfolderFormPanel.render();
}

function renderRenameFolderForm(node) {
    Ext.getDom("main-content-folder-rename").innerHTML = "";
    var uri = node.attributes.uri;
    var originalName = node.attributes.name;
    var parentNodeId = node.parentNode.id;

    var renameFolderFormPanel = new Ext.form.FormPanel({
        id: 'folderRenameSubForm',
        title: 'Rename Folder',
        method: 'POST',
        applyTo: "main-content-folder-rename",
        border: true,
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                autoWidth: true,
                border: false,
                items: [
                    new Ext.form.TextField({
                        fieldLabel: 'New Name',
                        defaultAutoCreate : {tag:"input", size: "40", autocomplete: "off"},
                        name: 'renameFolder',
                        id: 'renameFolderId',
                        allowBlank: false,
                        listeners:{
                            focus: function(tf) {
                                Ext.getCmp("renameFolderButtonId").enable();
                            }
                        }
                    }),
                    new Ext.Button({
                        id: 'renameFolderButtonId',
                        text: 'Update',
                        disabled: false,
                        listeners: {
                            click: function() {
                                var newFolderName = Ext.getCmp("renameFolderId").getValue();
                                if (newFolderName != null && newFolderName != '') {
                                    var postUrl = uri + "/rename";
                                    Ext.Ajax.request({
                                        url: postUrl,
                                        method: "POST",
                                        params: {
                                            "new_name": newFolderName
                                        },
                                        success: function() {
                                            eventManager.fireStatusMessageEvent({ text: "Folder renamed to: " + newFolderName, level: "info" });
                                            node.attributes.uri = uri.substring(0, uri.lastIndexOf(originalName)) + newFolderName;
                                            node.attributes.name = newFolderName;
                                            eventManager.fireNodeSelectEvent(node);
                                            expandNode(tree.getNodeById(parentNodeId));
                                        },
                                        failure: function() {
                                            eventManager.fireStatusMessageEvent({ text: "Failed to rename", level: "error" });
                                        }
                                    });
                                } else {
                                    Ext.MessageBox.alert("New Folder name can not be blank");
                                }
                            }
                        }
                    })
                ]
            })
        ]
    });
}


function renderUploadFileForm(node)
{
    Ext.getDom("main-content-folder-upload").innerHTML = "";
    var uri = node.attributes.uri;

    var uploadFileFormComponent = new Ext.form.FormPanel({
        id: 'folderUploadFileForm',
        title: 'Upload File',
        renderTo: "main-content-folder-upload",
        method: 'POST',
        fileUpload : true,
        border: true,
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                autoWidth: true,
                border: false,
                items: [
                    new Ext.form.TextField({
                        fieldLabel: 'Select file',
                        defaultAutoCreate : {tag:"input", enctype:"multipart/form-data", type:"file", size: "35", autocomplete: "off"},
                        name: 'FILE',
                        id: 'uploadFileNameId',
                        allowBlank: false,
                        listeners:{
                            change: function(t) {
                                Ext.getCmp("uploadFileButtonId").enable();
                            }
                        }
                    }),
                    new Ext.Button({
                        id: 'uploadFileButtonId',
                        text: 'Upload',
                        disabled: false,
                        listeners: {click:
                                function() {
                                    var formPanel = Ext.getCmp('folderUploadFileForm');
                                    var uploadFileName = Ext.getCmp("uploadFileNameId").getValue();
                                    if (uploadFileName == undefined || uploadFileName.length < 1) {
                                        Ext.MessageBox.alert("File must be selected before uploading");
                                        return false;
                                    }
                                    //this check is for IE/Chrome
                                    if (uploadFileName.indexOf("fakepath") != -1){
                                        var tks = uploadFileName.split("\\");
                                        uploadFileName = tks[tks.length - 1];
                                    }
                                    //check to see if file exists before                                    
                                    var uploadFileUrl = uri + "/" + uploadFileName;
                                    Ext.Ajax.request({
                                        url: uploadFileUrl + "/meta",
                                        method: "GET",
                                        success: function() {
                                            Ext.MessageBox.confirm('Message', 'File ' + uploadFileName + ' exists, upload new version?', function(btn) {
                                                if (btn == 'yes') {
                                                    upload(node, formPanel, uri, uploadFileName);
                                                } else {
                                                    eventManager.fireStatusMessageEvent({ text:'File upload cancelled', level: "info" });
                                                    return true;
                                                }
                                            });
                                        },
                                        failure: function(response) {
                                            var status = response.status;
                                            if (status == '404') {
                                                upload(node, formPanel, uri, uploadFileName);
                                            }
                                        }
                                    });
                                }
                        }
                    })
                ]
            })
        ]
    });
    uploadFileFormComponent.render();
}

var upwin = new Ext.Window({
    title: 'Upload Status',
    id: 'uploadwinid',
    width: 400,
    minWidth: 350,
    height: 150,
    modal: true,
    //closeAction: 'hide',
    bodyStyle: 'padding:10px;',
    html: "File uploading...",
    bbar: new Ext.ux.StatusBar({
        id: 'upload-file-statusbar',
        defaultText: 'Ready'
    })
});
upwin.on("show", function () {
    var sb = Ext.getCmp("upload-file-statusbar");
    sb.showBusy();
});

function upload(node, formPanel, uri, fileName) {
    upwin.show()
    formPanel.getForm().submit({
        clientValidation: true,
        url: uri,
        params: {
            "NO_RESPONSE": true
        },
        success: function(form, action) {
            eventManager.fireStatusMessageEvent({ text:  "File Uploaded Successfully", level: "info" });
            upwin.close();
            expandNode(node);
            eventManager.fireNodeSelectEvent(node);
        },
        failure: function(form, action) {
            eventManager.fireStatusMessageEvent({ text:  "File Upload Failed", level: "error" });
            upwin.close();
            expandNode(node);
            eventManager.fireNodeSelectEvent(node);
        }
    });

}
